<template>
  <div class="wrap">
    <div class="bar1" ref="crosswise"></div>
  </div>
</template>
<script>
import mixinData from "../utils/mixin.js";

export default {
  //mixin混入
  mixins: [mixinData],
  methods: {
    async getData() {
      //获取业务数据
      let res = await this.$http.get("cropAreasProportion");
      this.data = res.data;
      // console.log(this.data);
      this.getEcharts();
    },
    getEcharts() {
      //创建echarts实例
      this.echarts = this.$echarts.init(this.$refs.crosswise, this.themeName);
      // console.log(this.themeName)
      let data = this.data.map((item, index) => {
        return {
          type: "pie",
          label: {
            position: "center",
          },
          radius: [50, 70],
          center: [(100 / 5) * (index + 1) + "%", "50%"],
          data: [
            { name: item.areas + "\n" + item.zb + "%", value: item.zb },
            { value: item.other },
          ],
        };
      });
      // console.log(data);
      //设置配置项
      let option = {
        title: {
          text: "▍主要地区农作物种植占比",
        },
        series: data,
      };
      this.echarts.setOption(option);
      this.resize();
    },
    resize() {
      // 获取一个比例尺
      let width = this.$refs.crosswise.offsetWidth;
      // 3.5-3.7
      let scale = (width / 100) * 3.6;
      // 返回绘制每个饼图的系列对象 {type,center,radius,data}
      let data = this.data.map(() => {
        return {
          label: {
            fontSize: scale / 2,
          },
          radius: [scale * 1.7, scale * 2],
        };
      });
      // 根据比例尺动态设置标题、系列
      let updateOption = {
        title: {
          textStyle: {
            fontSize: scale,
          },
        },
        // 系列
        series: data,
      };
      this.echarts.setOption(updateOption);
      this.echarts.resize();
    },
  },
  mounted() {
    // console.log(this.$store.state.themeName);
    this.getData();
    //一进来就监听窗口变化
    window.addEventListener("resize", this.resize);
  },
  destroyed() {
    window.removeEventListener("resize", this.resize);
  },
};
</script>
<style scoped>
</style>